<?php
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------

namespace app\api\logic;

use app\common\logic\LogicBase;
use \tpfcore\Core;
use think\Validate;

class Posts extends ApiBase
{
    public function get_List($data = [])
    {
        $validate = \think\Loader::validate($this->name);
        $validate_result = $validate->scene('getlist')->check($data);
        if (!$validate_result) {
            return [4003, $validate->getError(), []];
        }

        $order = isset($data['sort']) ? $data['sort'] : 'id desc';
        $page = isset($data['page']) ? (int)$data['page'] : 1;
        $limit = isset($data['limit']) ? (int)$data['limit'] : 10;

        $nav_title = Core::loadModel("Category")->getList(["where"=>['parentid'=>$data['category_id']],"field"=>"id,title"]);

        $categorys = $this->getSonCateGoryIds($data['category_id']);

        if (empty($nav_title)) {
            $nav_title = Core::loadModel("Category")->field('id,title')->whereIn('id', $categorys)->select();
        }

        if(isset($data['init']) && $data['init']==1 && count($categorys)>1) $categorys=[$categorys[1]];

        $list = Core::loadModel('Posts')->getList(
            [
                'where' => ['cateid' => ['in', $categorys],"isdelete"=>0,"ischeck"=>1],
                'field' => ['content', true],
                'order' => $order,
                'paginate' => ['rows' => $limit, 'config' => ['query' => request()->param()]],
            ]
        );
        
        $list = $list->toArray();

        $list['current_cid']=$data['category_id'];

        $list['nav_title']=$nav_title;

        return [0, 'success', $list];
    }

    /**
    * 取分类下第一个子分类的数据，如果没有子分类，就取该分类下的数据
    */
    public function getPosts($data = [])
    {
        $order = $data['sort'] = isset($data['sort']) ? $data['sort'] : 'id desc';
        $page = $data['page'] = isset($data['page']) ? (int)$data['page'] : 1;
        $limit = $data['limit'] = isset($data['limit']) && !empty($data['limit']) ? (int)$data['limit'] : 10;

        $validate = \think\Loader::validate($this->name);
        $validate_result = $validate->scene('getlist')->check($data);
        if (!$validate_result) {
            return [4003, $validate->getError(), []];
        }

        $category_model=Core::loadModel("Category");

        $category_one = $category_model->getOneObject(["id"=>$data['category_id']]);

        if(empty($category_one)){

            return [40044,"非法的分类id"];

        }

        // 查询子分类
        $nav_title = $category_model->getList(["where"=>['parentid'=>$data['category_id']],"field"=>"id,title"]);

        if (empty($nav_title)) {
            $category_id = $data['category_id'];
        } else {
            $category_id = $nav_title[0]['id'];
        }

        $categorys = $this->getSonCateGoryIds($category_id);

        if (empty($nav_title)) {
            $nav_title = Core::loadModel("Category")->field('id,title')->whereIn('id', $categorys)->select();
        }

        $paginate = $category_one['channel_id'] == 3?['rows' => null, 'simple' => false, 'config' => []]:['rows' => $limit, 'config' => ['query' => request()->param()]];

        $field=['id','title','updatetime','thumb','source','author','view','likes','cateid','uid','abstract'];

        $field=isset($data['has_body']) && $data['has_body']==1?[implode(",", $field).",content"]:[implode(",", $field)];

        $list = Core::loadModel('Posts')->getList(
            [
                'where' => ['cateid' => ['in', $categorys],"isdelete"=>0,"ischeck"=>1],
                'field' => $field,
                'order' => $order,
                'paginate' => $paginate,
            ]
        );

        /*
            查询视频列表须要查询出所有视频
        */
        if($category_one['channel_id'] == 3){
            $posts_ids=[];
            foreach ($list as $key => $value) {
                $posts_ids[]=$value->id;
            }
            $list = Core::loadModel('PostsVideos')->getList(
                [
                    'where' => ['posts_id' => ['in', $posts_ids]],
                    'order' => $order,
                    'paginate' => ['rows' => $limit, 'config' => ['query' => request()->param()]],
                ]
            );
        }
        
        $list = $list->toArray();

        $list['current_cid']=$data['category_id'];

        $list['nav_title']=$nav_title;

        return [0, 'success', $list];
    }

    public function getSonCateGoryIds($cateid, $isSelf = true)
    {
        $ids = \think\Db::name('Category')->where('parentid', $cateid)->column('id');

        if ($isSelf) {
            array_unshift($ids, $cateid);
        }

        return $ids;
    }

    public function detail($data = [])
    {
        if (!isset($data['id']) || empty($data['id'])) {
            return [4003, 'ID不能为空', []];
        }

        $PostsModel = Core::loadModel('Posts');

        $posts = $PostsModel->getList([
            "field"=>"__POSTS__.*,__CATEGORY__.title ctitle,__CATEGORY__.channel_id",
            "where"=>["__POSTS__.id"=>$data['id']],
            "join"=>["join"=>"__CATEGORY__","condition"=>"__CATEGORY__.id=__POSTS__.cateid","type"=>"left"]
        ]);
        
        if(empty($posts)){
            return [4004, '数据不存在', []];
        }

        if($posts[0]->channel_id==2){
            $posts[0]->posts_images;
        }
        if($posts[0]->channel_id==3){
            $posts[0]->posts_videos;
        }

        if(!empty($data['open_id'])){

            $posts_log_model=Core::loadModel("PostsLog");

            $result = $posts_log_model->getOneObject(['posts_id'=>$data['id'],"open_id"=>$data['open_id'],"type"=>2]);

            if($result){

                $posts[0]->is_view=1;

            }else{

                $posts_log['posts_id']=$data['id'];
                $posts_log['open_id']=$data['open_id'];
                $posts_log['type']=2;

                $posts_log_model->saveObject($posts_log);

                $posts[0]->view=$posts[0]->view+1;

                $PostsModel->where(["id"=>$data['id']])->setInc("view");

            }
        }

        return [0, 'success', $posts];
    }

    public function add_view($data = []){
        $validate = \think\Loader::validate($this->name);
        $validate_result = $validate->scene('add_view')->check($data);
        if (!$validate_result) {
            return [4003, $validate->getError(), []];
        }

        $posts_model=Core::loadModel($this->name);

        $posts_one = $posts_model->getOneObject(["id"=>$data['posts_id']],"id,view");

        $posts_log_model=Core::loadModel("PostsLog");

        $result = $posts_log_model->getOneObject(['posts_id'=>$data['posts_id'],"open_id"=>$data['open_id'],"type"=>2]);

        if($result){
            return [-1, '已经浏览过了', ["view"=>$posts_one->view]];
        }

        $result = $posts_log_model->saveObject($data);

        if($result){

            $posts_model->where(["id"=>$data['posts_id']])->setInc("view");

            return [0, 'success', ["view"=>$posts_one->view+1]];
        }else{
            return [40048, '操作失败', []];
        }
    }

    public function add_likes($data = [])
    {
        $validate = \think\Loader::validate($this->name);
        $validate_result = $validate->scene('set_Likes')->check($data);
        if (!$validate_result) {
            return [4003, $validate->getError(), []];
        }

        $posts_model=Core::loadModel($this->name);

        $posts_one = $posts_model->getOneObject(["id"=>$data['posts_id']],"id,likes");

        $posts_log_model=Core::loadModel("PostsLog");

        $result = $posts_log_model->getOneObject(['posts_id'=>$data['posts_id'],"open_id"=>$data['open_id'],"type"=>1]);

        if($result){
            return [-1, '已经点过赞了', ["likes"=>$posts_one->likes]];
        }

        $result = $posts_log_model->saveObject($data);

        if($result){

            $posts_model->where(["id"=>$data['posts_id']])->setInc("likes");

            return [0, 'success', ["likes"=>$posts_one->likes+1]];
        }else{
            return [40048, '操作失败', []];
        }
    }

    public function search_data($data = [])
    {
        $validate = \think\Loader::validate($this->name);
        $validate_result = $validate->scene('search')->check($data);
        if (!$validate_result) {
            return [4003, $validate->getError(), []];
        }

        $page = isset($data['page']) ? (int)$data['page'] : 1;
        $limit = isset($data['limit']) ? (int)$data['limit'] : 10;

        $keyword = trim($data['keyword']);
        $MiniProgramCategoryId = db('Category')->where('title', '小程序数据栏目')->order('id asc')->value('id');
        $CategoryIds = $this->getSonCateGoryIds($MiniProgramCategoryId);

        $list = Core::loadModel('Posts')->getList(
            [
                'where' => ['cateid' => ['in', $CategoryIds], 'title' => ['like', "%{$keyword}%"]],
                'field' => ['content', true],
                'order' => 'id desc',
                'paginate' => ['rows' => $limit, 'config' => ['query' => request()->param()]],
            ]
        );

        return [0, 'success', $list];
    }
}